AS	=as --32
LD	=ld
LDFLAGS	=-m elf_i386
CC	=gcc -march=i386
CFLAGS	=-Wall -O2 -m32 -fomit-frame-pointer -fno-stack-protector

default: all

ARCHIVES=kernel/kernel.o
DRIVERS =kernel/chr_drv/chr_drv.a

.c.s:
	$(CC) $(CFLAGS) \
	-nostdinc -Iinclude -S -o $*.s $<
.s.o:
	$(AS) -c -o $*.o $<
.c.o:
	$(CC) $(CFLAGS) \
	-nostdinc -Iinclude -c -o $*.o $<

all: Image

Image: clean mkimg boot/bootsect.bin boot/setup.bin system
	objcopy -O binary -R .note -R .comment system kernel.bin
	dd if=boot/bootsect.bin of=kernel.img bs=512 count=1 conv=notrunc
	dd if=boot/setup.bin of=kernel.img bs=512 count=4 seek=1 conv=notrunc
	dd if=kernel.bin of=kernel.img bs=512 count=384 seek=5 conv=notrunc
	rm kernel.bin -f
	bochs -qf bochsrc

boot/head.o: boot/head.s
	gcc -m32 -traditional -c boot/head.s -o boot/head.o

system:	boot/head.o init/main.o $(ARCHIVES) $(DRIVERS)
	$(LD) $(LDFLAGS) boot/head.o init/main.o \
	$(ARCHIVES)	\
	$(DRIVERS)	\
	-o system -T kernel.lds
	nm system | grep -v '\(compiled\)\|\(\.o$$\)\|\( [aU] \)\|\(\.\.ng$$\)\|\(LASH[RL]DI\)'| sort > System.map 

kernel/chr_drv/chr_drv.a:
	(cd kernel/chr_drv; make)

kernel/kernel.o:
	(cd kernel; make)

boot/bootsect.bin: boot/bootsect.s
	nasm boot/bootsect.s -o boot/bootsect.bin

boot/setup.bin: boot/setup.s
	nasm boot/setup.s -o boot/setup.bin

mkimg:
	./mkimg.sh

clean:
	rm -rf boot/*.bin boot/*.o init/*.o System.map system kernel.img
	(cd kernel;make clean)

init/main.o: init/main.c
	$(CC) $(CFLAGS) -nostdinc -Iinclude -c -o $*.o $<
